package com.hxzy.config.inteceptor;

import cn.hutool.core.util.StrUtil;
import com.hxzy.common.constans.MarketingConstans;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.util.*;
import com.hxzy.controller.mobile.login.resp.MobileLoginResp;
import com.hxzy.controller.vue.login.resp.AdminLoginResp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author wy
 * @Description 手机端令牌拦截器
 * @Date 2023/8/29 16:58
 * @Version 1.0
 */
@Component
public class MobileTokenValidateHandlerInterceptor implements HandlerInterceptor {

    @Autowired
    private MobileMultipleTokenService  mobileMultipleTokenService;


    /**
     * 是否为要令牌续时
     */
    @Value(value = "${token.duration}")
    private boolean duration;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取令牌
        String jwtToken=request.getHeader(MarketingConstans.ADMIN_HEADER);

        if(StrUtil.isBlank(jwtToken)){
            ServletUtil.outJson(response, AckCode.TOKEN_NOT_BLANK);
            return false;
        }

        //从缓存中获取值
        MobileLoginResp loginResp= this.mobileMultipleTokenService.getLoginResp(jwtToken);

        if(loginResp==null){
            ServletUtil.outJson(response,AckCode.APPLE_EXPIRED);
            return false;
        }

        //要不要开启续时功能
        if(duration){
            mobileMultipleTokenService.verifyToken(loginResp);
        }

        //存储到本地线程，供后面的使用
        MarketingThreadLocalUtil.mobileThreadLocal.set(loginResp);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        MarketingThreadLocalUtil.mobileThreadLocal.remove();
    }
}
